# config.py -- for handling the site/application configuration
# ---------------------------------------------------------------------------
# by Sean A. Harrison <sah@tyndale.com>
# $Id: config.py 94 2013-07-31 20:39:13Z sah.harrison@gmail.com $

import os
from ConfigParser import ConfigParser
from amplitude.dict import Dict         # needed for dot-attribute notation

class SiteConfig(Dict):
    """class for holding a site configuration.
    >>> cf = SiteConfig('config_test.ini')
    >>> cf.value('Database', 'adaptor') is not None
    True
    >>> exec("import %s as dba" % cf.value('Database', 'adaptor'))
    >>> conn = dba.connect(cf.value('Database', 'connection'))
    """

    def __init__(self, configfilepath):
        cp = ConfigParser({}, Dict, True)
        if cp.read([configfilepath]):
            self.parse_config(cp)
            self.site_root = os.path.dirname(configfilepath)
        else:
            raise KeyError, "Config file not found at %s" % configfilepath

    def parse_config(self, configparser):
        for s in configparser.sections():
            self[s] = Dict()
            for k, v in configparser.items(s):
                self[s][k] = v.decode('UTF-8')

    def value(self, section, key):
        if section in self and key in self[section]:
            return self[section][key]
        else:
            return None

    def connect_to_db(self):
        from amplitude.db import Database
        if self.Database.adaptor is None or 'sqlite' in self.Database.adaptor:
            dbfn = os.path.join(self.site_root, self.Database.filename)
            return Database(dbfn)
        else:            
            return Database(self.Database.connection, self.Database.adaptor, config=self)

if __name__ == "__main__":
    import doctest
    doctest.testmod()
